package logic

import (
	"common/global"
	"common/model"
	"context"
	"fmt"
	user "user_server/proto"

	"time"
)

// 新增查询方法到UserServer结构体
func (s *UserServer) GetLuckyDrawRecords(ctx context.Context, req *user.GetLuckyDrawRecordsRequest) (*user.GetLuckyDrawRecordsResponse, error) {
	var records []model.LuckyDrawRecord
	var total int64

	// 分页查询
	//根据用户ID进行分页查询，获取抽奖记录总数。
	tx := global.Db.Model(&model.LuckyDrawRecord{}).Where("user_id = ?", req.UserId)
	tx.Count(&total)
	//执行分页查询，获取指定页码和页大小的抽奖记录。
	err := tx.Offset(int((req.Page - 1) * req.PageSize)).
		Limit(int(req.PageSize)).
		Find(&records).Error

	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}

	//将查询到的抽奖记录转换为proto结构。
	var resRecords []*user.LuckyDrawRecord
	for _, r := range records {
		resRecords = append(resRecords, &user.LuckyDrawRecord{
			PrizeName: r.PrizeName,
			CreatedAt: r.CreatedAt.Format(time.RFC3339),
		})
	}
	//构建并返回包含抽奖记录和总数的响应。
	return &user.GetLuckyDrawRecordsResponse{
		Records: resRecords,
		Total:   int32(total),
	}, nil
}
